import cookies from "./util.cookies";

const util = {
  cookies
};

/**
 * @description 更新标题
 * @param {String} title 标题
 */
util.title = function(titleText) {
  const processTitle = process.env.WEBSITE_NAME || "D2Admin";
  window.document.title = `${processTitle}${
    titleText ? ` | ${titleText}` : ""
  }`;
};

/**
 * @description 打开新页面
 * @param {String} url 地址
 */
util.open = function(url) {
  var a = document.createElement("a");
  a.setAttribute("href", url);
  a.setAttribute("target", "_blank");
  a.setAttribute("id", "d2admin-link-temp");
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(document.getElementById("d2admin-link-temp"));
};

util.getQueryString = function(name) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
  var r = window.location.search.substr(1).match(reg);
  if (r != null) return unescape(r[2]);
  return null;
};

// 生产id
util.newId = () => {
  var index = window.index || 0;
  // var index = index + 1;
  // window.index = index;
  // return index;
  return `${util.rand(8)}`;
};

// 随机生成长度等于len的字符串
util.rand = len => {
  var s = "";
  while (s.length < len && len > 0) {
    var r = Math.random();
    s += String.fromCharCode(Math.floor(r * 26) + (r > 0.5 ? 97 : 65));
  }
  return s;
};

// 禁止微信H5下拉
util.wxH5DragDownForbidden = function(el) {
  const app = el;
  let touchstartY;
  app.addEventListener(
    "touchstart",
    function(event) {
      var events = event.touches[0] || event;
      touchstartY = events.clientY; //获取触摸目标在视口中的y坐标
    },
    false
  );

  app.addEventListener(
    "touchmove",
    function(event) {
      var events = event.touches[0] || event;
      //注意app.scrollTop始终为0
      var scrollTop = app.scrollTop || document.documentElement.scrollTop; //获取滚动部分的高度
      var clientHeight = document.documentElement.clientHeight; //获取手机屏幕高度（可视部分高度）
      var scrollHeight = app.scrollHeight; //所有内容的高度
      if (events.clientY > touchstartY && scrollTop === 0 && event.cancelable) {
        event.preventDefault(); //禁止到顶下拉
      } else if (scrollTop + clientHeight > scrollHeight && event.cancelable) {
        // event.preventDefault(); //禁止到底上拉
      }
    },
    false
  );
};

util.isWeixin = function() {
  //判断是否是微信
  var ua = navigator.userAgent.toLowerCase();
  return ua.match(/MicroMessenger/i) == "micromessenger";
};

export default util;
